﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BLL;
using DLL;
using Helper;
using Logging;

namespace QuanLyBanLe
{
    public partial class FormUserMgr : Form
    {
        private bool m_isChanged;
        private bool m_loadCompleted;
        private UserService m_Service;

        public FormUserMgr()
        {
            InitializeComponent();
            m_isChanged = false;
            m_loadCompleted = false;
            m_Service = new UserService();
        }

        private void FormUserMgr_Load(object sender, EventArgs e)
        {
            dtgUser.AutoGenerateColumns = false;
            List<User> users = m_Service.GetAllUsers();
            int i = 0;
            foreach (User user in users)
            {
                dtgUser.Rows.Add(1);
                DataGridViewRow row = dtgUser.Rows[i];
                row.Cells["colId"].Value = user.Id;
                row.Cells["colUsername"].Value = user.Username;
                row.Cells["colPassword"].Value = user.Password;
                row.Cells["colRole"].Value = user.UserTypeId;
                i++;
            }

            colRole.DataSource = m_Service.GetAllUserTypes();
            colRole.ValueMember = "Id";
            colRole.DisplayMember = "Name";
            this.Text += FormMain.GetShopInfo();
            m_loadCompleted = true;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dtgUser_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (m_loadCompleted)
            {
                if (e.ColumnIndex == dtgUser.Columns["colDelete"].Index)
                {
                    DialogResult result = MessageBox.Show("Bạn có chắc muốn xóa người dùng này", "Thông báo",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == DialogResult.Yes)
                    {
                        var currentRow = dtgUser.Rows[e.RowIndex];
                        var temp = currentRow.Cells["colId"].Value;
                        if (temp != null)
                        {
                            int userId = 0;
                            if (int.TryParse(temp.ToString(), out userId))
                            {
                                m_Service.DeleteUser(userId);
                            }
                            dtgUser.Rows.RemoveAt(currentRow.Index);
                        }
                    }
                }
            }
        }

        private void dtgUser_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (m_loadCompleted)
            {
                if (dtgUser.Rows[e.RowIndex].IsNewRow) { return; }

                dtgUser.Rows[e.RowIndex].ErrorText = "";
                // validate password
                if (e.ColumnIndex == dtgUser.Columns["colPassword"].Index)
                {
                    if (e.FormattedValue == null || string.IsNullOrWhiteSpace(e.FormattedValue.ToString()))
                    {
                        e.Cancel = true;
                        dtgUser.Rows[e.RowIndex].ErrorText = "Nhập mật khẩu";
                    }
                }

                if (e.ColumnIndex == dtgUser.Columns["colUsername"].Index)
                {
                    if (e.FormattedValue == null || string.IsNullOrWhiteSpace(e.FormattedValue.ToString()))
                    {
                        e.Cancel = true;
                        dtgUser.Rows[e.RowIndex].ErrorText = "Nhập tên";
                    }
                }
            }
        }

        private void dtgUser_RowValidated(object sender, DataGridViewCellEventArgs e)
        {
            if (m_loadCompleted)
            {
                SaveOrUpdateUser(e.RowIndex);
            }
        }

        private void dtgUser_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (m_loadCompleted)
            {
                m_isChanged = true;
            }
        }

        private void SaveOrUpdateUser(int rowNumber)
        {
            if (m_isChanged)
            {
                try
                {
                    var row = dtgUser.Rows[rowNumber];
                    int? userId = Convert.ToInt32(row.Cells["colId"].Value);
                    if (userId.HasValue && userId.Value > 0)
                    {
                        // update user
                        User user = new User
                        {
                            Id = userId.Value,
                            Username = row.Cells["colUsername"].Value.ToString(),
                            Password = Encrypt.Hash(row.Cells["colPassword"].Value.ToString()),
                            UserTypeId = Convert.ToInt32(row.Cells["colRole"].Value)
                        };
                        m_Service.UpdateUser(user);
                    }
                    else
                    {
                        // add user
                        User user = new User
                        {
                            Username = row.Cells["colUsername"].Value.ToString(),
                            Password = Encrypt.Hash(row.Cells["colPassword"].Value.ToString()),
                            UserTypeId = Convert.ToInt32(row.Cells["colRole"].Value)
                        };
                        m_Service.AddUser(user);
                        row.Cells["colId"].Value = user.Id;
                    }
                }
                catch (Exception ex)
                {
                    MyLogger.LogException("Lỗi xảy ra khi thêm/cập nhật user: " + ex.Message, ex);
                }
                m_isChanged = false;

            }
        }

        private void dtgUser_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (dtgUser.Rows[e.RowIndex].IsNewRow) { return; }

            DataGridViewRow row = dtgUser.Rows[e.RowIndex];
            var userName = row.Cells["colUsername"].Value;
            if (userName == null || string.IsNullOrWhiteSpace(userName.ToString()))
            {
                e.Cancel = true;
                dtgUser.Rows[e.RowIndex].ErrorText = "Nhập tên";
            }
            if (!e.Cancel)
            {
                var password = row.Cells["colPassword"].Value;
                if (password == null || string.IsNullOrWhiteSpace(password.ToString()))
                {
                    e.Cancel = true;
                    dtgUser.Rows[e.RowIndex].ErrorText = "Nhập mật khẩu";
                }
            }
            if (!e.Cancel)
            {
                var role = row.Cells["colRole"].Value;
                if (role == null)
                {
                    e.Cancel = true;
                    dtgUser.Rows[e.RowIndex].ErrorText = "Chọn quyền";
                }
            }
        }
    }
}
